<template>
    <div>
        <el-page-header @back="goBack">
            <div slot="content" style="display: flex;align-items: center;">
                <div>查看采购单</div>
                <div style="margin-left: 12px;" v-if="!pageType">
                    <div v-if="formData.is_pay" style="border: 1px solid #0099ff;color: #0099ff;font-size: 12px;padding: 0 5px;border-radius: 2px;">已结清</div>
                    <div v-else style="border: 1px solid #f55;color: #f55;font-size: 12px;padding: 0 5px;border-radius: 2px;">未结清</div>
                </div>
            </div>
        </el-page-header>
        <!-- <div class="common_line"></div> -->
        <el-form ref="formData" :model="formData" label-width="auto" style="margin-top: 20px;width: 85%;">
            <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;">基本信息</div>
            <el-row>
                <el-col :span="6">
                    <el-form-item label="供货商名称:">
                        <div>{{ formData.supplierName }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="采购日期:">
                        <div>{{ formData.purchase_date }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="采购编号:">
                        {{ formData.corp_order_no }}
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="经办人:">
                        <div>{{ formData.handler_name }}</div>
                    </el-form-item>
                </el-col>
            </el-row>

            <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;">采购商品</div>
            <el-row>
                <el-table :data="formData.goods" border style="margin-top: 15px;">
                    <el-table-column label="序号" width="80" align="center" prop="index" />
                    <el-table-column label="商品名称" align="center" prop="name" />
                    <el-table-column label="商品编号" align="center" prop="goods_no" />
                    <el-table-column label="数量" align="center" prop="num" />
                    <el-table-column label="单价" align="center" prop="unit_price" />
                    <el-table-column label="总额" align="center">
                        <template slot-scope="scope">
                            <div v-if="scope.row.num&&scope.row.unit_price">
                                {{ (parseFloat(scope.row.num)*parseFloat(scope.row.unit_price)).toFixed(2) }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="单位" align="center" prop="unitName" />
                    <el-table-column label="批次" align="center" prop="batch_name" />
                    <el-table-column label="生产日期" align="center" prop="produce_date" />
                    <el-table-column label="规格" align="center" prop="specifications" />
                    <el-table-column label="库存剩余" align="center" prop="current_inventory_quantity" />
                </el-table>
            </el-row>
            
            <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;">价格明细</div>
            <el-row>
                <el-col :span="6">
                    <el-form-item label="商品总价:">
                        <div>{{ '￥'+formData.standard_price }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="总数量:">
                        <div>{{ formData.quantity }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="结款优惠:">
                        <div>{{ '￥'+formData.payment_discount }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="采购金额:">
                        <div style="color: red;">{{ '￥'+formData.sold_price }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="待付款:">
                        <div style="color: red;">{{ '￥'+formData.unPayMoney }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="结算账户:">
                        <div>{{ paymentStr }}</div>
                    </el-form-item>
                </el-col>
            </el-row>

            <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;">其他信息</div>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="需要发票:">
                        {{ formData.is_need_invoice?'是':'否' }}
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="备注:">
                        {{ formData.remark }}
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="fileLists&&fileLists.length">
                <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;">附件</div>
                <div class="file_list">
                    <div v-for="item in fileLists" :key="'file_'+item.id" class="file" @click="downloadFile(item)">
                        {{ item.file_name }}
                    </div>
                </div>
            </el-row>
        </el-form>

        <!-- 付尾款弹窗 -->
        <el-dialog title="付款" :visible.sync="showPaymentPop" :close-on-click-modal="false" width="30%" center append-to-body>
            <div>
                <el-form :model="paymentForm" label-width="auto" ref="paymentForm" :rules="rules">
                    <el-form-item label="待付金额:">
                        <div>{{ '￥'+formData.unPayMoney }}
                            <span>{{ '(剩余待付 ￥'+lastReceive+')'}}</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="本次付款:" prop="orders_fee">
                        <el-input style="width: 280px;" maxlength="100" v-model="paymentForm.orders_fee" placeholder="请输入" clearable />
                    </el-form-item>
                    <el-form-item label="结算账户:">
                        <el-select style="width: 280px;" v-model="paymentForm.pay_type" placeholder="请选择">
                            <el-option v-for="item in payTypes" :key="'pay_'+item.value" 
                                :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="备注:">
                        <el-input maxlength="200" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 6 }"
                         v-model="paymentForm.remark" placeholder="请输入" style="width: 280px;" clearable />
                    </el-form-item>
                </el-form>  
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showPaymentPop=false">关 闭</el-button>
                <el-button class="btn_primary_color" @click="createReceiveOrder">确 定</el-button>
            </span>
        </el-dialog>

        <div class="bottom">
            <div class="btns" v-if="!pageType">
                <el-button class="btn btn_primary_color" v-if="!formData.is_pay" @click="showReceivedMoney">付尾款</el-button>
                <template v-if="formData.payment_record&&formData.payment_record.length">
                    <div class="record" @click="showRecord">付款记录</div>
                </template>
            </div>
            <div class="btns" v-else>
                <el-button v-if="pageType=='1'||pageType=='3'" class="btn btn_primary_color" @click="dealOrder('pass')">通过</el-button>
                <el-button v-if="pageType=='1'" class="btn btn_remove_color" @click="dealOrder('unpass')">驳回</el-button>
            </div>
        </div>

         <!-- 付款记录弹窗 -->
        <el-dialog title="付款记录" :visible.sync="showRecordAlert" :close-on-click-modal="false" width="30%" center append-to-body>
            <div style="padding-left: 40px">
                <el-timeline :reverse="false">
                    <el-timeline-item
                        v-for="(activity, index) in records"
                        :key="'rec_'+index"
                        :timestamp="activity.timestamp">
                        <div style="display: flex;align-items: center;justify-content: space-between;padding-right: 100px;">
                            <span>{{ activity.content }}</span>
                            <span>{{ activity.pay_type_str }}</span>
                        </div>
                    </el-timeline-item>
                </el-timeline>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showRecordAlert=false">关 闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { infoBuy } from '@/api/purchase';
import bottomBtns from "@/components/bottomBtns";
import { addPayment } from "@/api/cooperate";
import { todoApply } from '@/api/login'
const moment = require('moment')

export default {
    name: 'querypurchase',
    components: {
        bottomBtns
    },
    data() {
        return {
            showLoading: false,
            showRecordAlert: false,
            isEdit: false,
            corp: '',
            pageTitle: '',
            orderId: '',
            setForm: {},
            customFields: [],
            activeNames: ['base', 'product', 'price'],
            formData: {
                goods: [],
                standard_price: '',
                purchase_date: null,
                sold_price: 0,
                current_paid_payment: '',
                draft_payment: '',
                quantity: '',
                payment_discount: 0,
                pending_payment: '',
                handler_user: '',
                is_draft: false,
                is_pay: 1,
                remark: '',
                supplier: '',
                corp: '',
            },
            payTypes: [
                {label: '微信', value: 2},
				{label: '支付宝', value: 5},
				{label: '现金', value: 1},
				{label: '银行转账', value: 3},
				{label: '其他', value: 4}
            ],
            customerList: [],
            dialogTitle: '',
            chooseUsers: [],
            salesList: [],
            handlersList: [],
            chooseGoods: [],
            goodsList: [],
            pageParam: {
                page: 1,
                num: 10
            },
            total: 0,
            loadOver: false,  //是否加载完
            queryParams: {
                status: '',
                brand__icontains: '',
                type__icontains: '',
                specifications__icontains: '',
                category_one_level: '',
                category: '',
                search: ''
            },
            categorys: [],
            selectCates: [],
            exchangeId: null,  //预售转单id
            buttonList: [
                { name: '关闭', type: 'cancel', id:'3' }
            ],
            showPaymentPop: false,
            paymentForm: {
                corp: '',
                supplier: '',
                handler_user: '',
                orders_date: '',
                orders_fee: '',
                pay_type: 2,
                record_type: 2, //2付款--采购开单|1收款--采购退单
                remark: '',
                order_relations: []
            },
            rules:{
                orders_fee: [
                    { required: true, message: "请输入本次付款金额", trigger: 'blur' },
                ]
            },
            fileLists: [],
            records: [],
            pageType: '',
            todoId: ''
        }
    },
    props: {
        corpId: {
            type: Number
        },
        editId: {
            type: Number
        }
    },
    watch: {
        '$route.query.bussId5': {
            immediate: true, // 首次加载时触发
            handler(newId) {
                if (newId) {
                    this.corp = this.$store.state.corpId
                    this.orderId = newId
                    this.pageType = this.$route.query.type || ''
                    this.todoId = this.$route.query.todoId || ''
                    this.getOrderInfo()
                }
            }
        }
    },
    computed: {
        // 计算剩余待收
        lastReceive() {
            let res = parseFloat(this.formData.unPayMoney)
            if (this.paymentForm.orders_fee){
                res = this.$common.subtractFloat(parseFloat(this.formData.unPayMoney), parseFloat(this.paymentForm.orders_fee))
            }
            return res.toFixed(2)
        },
        paymentStr() {
            let str = '未支付'
            if (this.formData.payment_record && this.formData.payment_record.length){
                let names = this.formData.payment_record.map(item => item.pay_type_str)
                str = names.join('、')
            }
            return str
        }
    },
    mounted() {
        this.corp = this.corpId
        if (this.editId){
            this.orderId = this.editId
            this.getOrderInfo()
        }
    },
    methods: {
        goBack() {
            this.$emit('hidden', '')
        },
        downloadFile(item) {
            location.href = item.url_show
        },
        // 收尾款
        showReceivedMoney() {
            this.paymentForm.corp = this.formData.corp
            this.paymentForm.supplier = this.formData.supplier
            this.paymentForm.handler_user = this.formData.handler_user
            this.paymentForm.pay_type = 2
            this.paymentForm.orders_date = moment().format('yyyy-MM-DD')
            this.paymentForm.orders_fee = this.formData.unPayMoney
            this.paymentForm.remark = ''
            this.showPaymentPop = true
        },
        // 创建收款单
        createReceiveOrder() {
            if (parseFloat(this.paymentForm.orders_fee) > parseFloat(this.formData.unPayMoney)){
                this.$message.error('本次付款金额大于待付款金额，请重新输入')
                return
            }
            this.paymentForm.order_relations = [{
                related_order_id: this.orderId,
                orders_fee: parseFloat(this.paymentForm.orders_fee)
            }]

            addPayment(this.paymentForm).then(res => {
                if (res.code == 200){
                    let isShow = res.data.data.is_show
                    let msg = isShow?'付款成功':'付款成功，请等待审核员审核'
                    this.$message({
                        message: msg,
                        type: 'success'
                    })
                    this.getOrderInfo()
                    this.showPaymentPop = false
                }
            })
        },
        // 获取详情
        getOrderInfo() {
            let _this = this
            infoBuy(this.orderId,  {corp: this.corp}).then(res => {
                let infos = res.data.data
                _this.formData = infos
                _this.formData.supplierName = infos.supplier_detail.name
                _this.formData.is_pay = infos.is_pay==true?1:0
                _this.formData.remark = infos.remark?infos.remark:''
                if (infos.paid_payment){
                    _this.formData.unPayMoney = _this.$common.subtractFloat(parseFloat(infos.sold_price), parseFloat(infos.paid_payment))
                }else{
                    _this.formData.unPayMoney = 0
                }
                
                _this.formData.handler_name = infos.handler_user_detail ? infos.handler_user_detail.username : ''
                
                if (infos.draft_payment){
                    _this.$set(_this.formData, 'current_paid_payment', parseFloat(infos.draft_payment))
                    // _this.formData.current_paid_payment = parseFloat(infos.draft_payment)
                }
                // 附件
                _this.fileLists = infos.file_list_show || []

                _this.formData.builder = []
                _this.formData.sale = []
                _this.formData.goods = []

                let all_price = 0
                let all_count = 0
                if (infos.batch_date_record_detail && infos.batch_date_record_detail.length){  //商品
                    infos.batch_date_record_detail.forEach((item, index) => {
                        let allUnits = []
                        item.main_unit_name = item.goods_details.unit_show.name
                        item.main_unit_id = item.goods_details.unit_show.id
                        item.is_multi_unit = false
                        item.unitName = item.main_unit_name
                        item.selectUnitId = item.main_unit_id
                        item.unit_price = item.goods_details.unit_price
                        item.num = item.goods_details.num
                        if (item.deputy_unit) {  //多单位
                            item.unitName = item.deputy_unit_detail?item.deputy_unit_detail.unit_name:''
                            item.is_multi_unit = true
                            item.selectUnitId = item.deputy_unit_detail.goods_unit 
                            item.unit_price = parseFloat(item.deputy_price)
                            item.num = _this.$common.multiplyDivision(parseFloat(item.num), parseFloat(item.deputy_ratio)).toFixed(2)
                            let formatterName = '1'+item.unitName+'='+parseFloat(item.deputy_ratio)+item.goods_details.unit_show.name
                            item.deputy_unit_detail.formatterName = formatterName
                            item.deputy_unit_detail.unit_price = item.unit_price
                            let mainArray = [{
                                goods_unit: item.goods_details.unit_show.id,
                                unit_name: item.goods_details.unit_show.name,
                                formatterName: item.goods_details.unit_show.name,
                                unit_price: item.goods_details.unit_price,
                                unit_retail_price: item.goods_details.unit_retail_price || 0,
                                unit_purchase_price: item.goods_details.unit_purchase_price || 0
                            }]
                            let array = mainArray.concat([item.deputy_unit_detail])
                            allUnits = array.filter(_item => {
                                _item.select = _item.unit_name==item.unitName
                                return _item
                            })
                            item.unitName += ('('+formatterName+')')
                        }
                        
                        _this.formData.goods.push({
                            index: index+1,
                            name: item.goods_details.name,
                            id: item.goods_details.id,
                            num: parseFloat(item.num),
                            select_num: parseFloat(item.num),
                            unit: item.goods_details.unit,
                            unit_price: item.unit_price,
                            goods_no: item.goods_details.goods_no || '',
                            imageUrl: (item.goods_details.image?item.goods_details.image.url:'https://anhuiyaoying.com/icon/default.png'),
                            current_inventory_quantity: parseFloat(item.goods_details.current_inventory_quantity),
                            unitArray: allUnits,
                            select_unit_id: item.selectUnitId,
                            unitName: item.unitName,
                            main_unit_name: item.main_unit_name,
                            is_multi_unit: item.is_multi_unit,
                            is_start_batch: item.goods_details.is_start_batch,
                            is_start_sell_by_date: item.goods_details.is_start_sell_by_date,
                            produce_date: item.batch_date_account_detail?item.batch_date_account_detail.produce_date:'',
                            batch_name: item.batch_date_account_detail?item.batch_date_account_detail.batch_name:'',
                        })
                        all_count += parseFloat(item.goods_details.num)
                        all_price += (_this.$common.multiplyFloat(item.goods_details.num, item.goods_details.unit_price))
                    })
                }
                
                if (infos.standard_price) {
                    _this.formData.standard_price = parseFloat(infos.standard_price)
                }else{
                    _this.formData.standard_price = all_price
                }
                
                if (infos.quantity) {
                    _this.formData.quantity = parseFloat(infos.quantity)
                }else{
                    _this.formData.quantity = all_count
                }
                _this.formData.payment_discount = parseFloat(infos.payment_discount)
                _this.formData.sold_price = parseFloat(infos.sold_price)
            })
        },
        // 收款记录
        showRecord() {
            this.records = this.formData.payment_record.filter(item => {
                item.timestamp = item.update_datetime.substring(0, 16).replace('T', ' ')
                item.content = "已收：￥"+item.current_paid_payment
                return item
            })
            this.showRecordAlert = true
        },
        // 自定义按钮事件
        handleButtonClick(item) {
            switch (item.id) {
                case '3':   // 取消
                    this.goBack()
                    break;
            
                default:
                    break;
            }
        },
        // 处理待办
        dealOrder(type) {
            todoApply({
                todo_id: this.todoId,
                status: type=='pass'?'已通过':'驳回',
                corp_id: this.formData.corp
            }).then(res => {
                this.$message.success('处理成功')
                this.$emit('hidden', {isRefresh: 'true'})
            })
        }
    }
}
</script>

<style lang="less" scoped>
    @import '../../../style/mixin.less';
    .form_title {
        font-size: 14px;
        font-weight: bold;
        color: #333;
        padding: 15px 0;
    }
    .set_user_none {
        margin-left: 10px;
        font-size: 14px;
        color: @blue;
        &:hover {
            cursor: pointer;
        }
    }
    .set_user_done {
        margin-left: 10px;
        font-size: 14px;
        &:hover {
            color: @blue;
            cursor: pointer;
        }
    }
    .file_list {
        font-size: 13px;
        padding-left: 40px;
        .file {
            cursor: pointer;
            padding-bottom: 10px;
            &:hover {
                color: @blue;
            }
        }
    }
    .set_user_dialog {
        padding: 0 10px;
        max-height: 300px;
        overflow-y: auto;
        .item {
            display: flex;
            align-items: center;
            padding-bottom: 10px;
            justify-content: space-between;
            width: 90%;
            .btns {
                display: inline-flex;
                align-items: center;
                font-size: 20px;
                margin-left: 10px;
                width: 60px;
                .add {
                    color: @blue;
                    margin-right: 20px;
                    &:hover{
                        cursor: pointer;
                    }
                }
                .remove {
                    color: red;
                    &:hover{
                        cursor: pointer;
                    }
                }
            }
        }
    }
    .goods_add {
        display: flex;
        align-items: center;
        justify-content: end;
        padding-right: 20px;
        cursor: pointer;
        color: @blue;
        i {
            font-size: 16px;
        }
        span {
            margin-left: 8px;
            font-weight: bold;
            font-size: 14px;
        }
    }
    .goods_list {
        padding: 0 10px;
        max-height: 400px;
        overflow-y: auto;
    }
    .inner_input {
        width: 80px;
        height: 36px;
        line-height: 36px;
        font-size: 14px;
        border: 1px solid #DCDFE6;
        border-radius: 4px;
        background-color: #FFF;
        box-sizing: border-box;
        color: #606266;
        padding: 0 12px;
    }
    .record {
        color: @blue;
        cursor: pointer;
        font-size: 14px;
        padding-right: 20px;
        font-weight: 500;
        text-align: right;;
    }
    .bottom {
        position: fixed;
        bottom: 0;
        left: 150px;
        right: 0;
        height: 50px;
        background: #fff;
        border: 1px solid #eee; /* 边框 */
        box-shadow: 0 -3px 6px rgba(0, 0, 0, 0.5); /* 上边框阴影 */
        display: flex;
        align-items: center;
        justify-content: end;
        .btns {
            padding: 0 30px;
            display: flex;
            align-items: center;
            gap: 12px;
            .btn {
                height: 32px;
                display: inline-flex;
                align-items: center;
            }
        }
    }
</style>

<style>
.el-collapse-item__header {
    font-size: 14px;
    font-weight: bold;
}
.el-collapse-item__arrow {
    font-size: 18px;
}
</style>